package com.wksc.framework.impexp.reader;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import jxl.read.biff.BiffException;

/**
 * <p>
 * Title(文件名): ${file_name}
 * </p>
 * <p>
 * Description(描述): ${todo}
 * </p>
 * <p>
 * Copyright(版权): Copyright (c) ${year}
 * </p>
 * <p>
 * Company(公司): 成都四方信息技术有限公司
 * </p>
 * <p>
 * CreateTime(生成日期)：11-11-13下午4:23
 * </p>
 * 
 * @author wanglei
 * @version ${project_name}
 */
public class TxtReader extends Reader {

	private List<String> dataList = new ArrayList<String>(5000);

	protected TxtReader() {
		super();
	}

	@Override
	public int countTotalLine() {
		return dataList.size();
	}

	@Override
	public String[] readByRow(int lineNum) {
		String lineContent = dataList.get(lineNum);
		// 以逗号分隔将字符串转换为字符串数组
		return lineContent.split("(?<!\\\\)&&", -1);
	}

	@Override
	public void close() {

	}

	@Override
	protected void initFile() throws BiffException, IOException {
		String charSet = "utf-8";
		InputStream inputStream = new FileInputStream(this.file);
		InputStreamReader inputStreamReader = new InputStreamReader(
				inputStream, charSet);
		BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
		//		String line = bufferedReader.readLine(); //findbug报错改为下面的方式 
		boolean firstLineIsNull = false;
		String line = bufferedReader.readLine(); //第一行
		if (line == null) {
			firstLineIsNull = true;
		} else {
			if (line.length() > 0 && !line.contains("@")) { //实际应该是line.indexOf("@")>2 || ==-1 (-1 不包含 1以@开头,无bom 2以@开头,有bom)
				if (line.trim().length() > 1) { //3个字符(字母)以下都可以认为是bom头,这个地方使用1个字母一下,因为bom头经utf-8读取为1个字符
					dataList.add(line);
				}
			}
		}
		if (!firstLineIsNull) {
			while ((line = bufferedReader.readLine()) != null) { //第二行以后
				if (line.trim().length() > 0 && !line.startsWith("@")) {
					dataList.add(line);
				}
			}
		}
		bufferedReader.close();
		inputStreamReader.close();
		inputStream.close();
	}
}
